package framework.core
{
import flash.display.DisplayObject;
import flash.system.ApplicationDomain;
import flash.utils.Dictionary;

import framework.binding.IBinder;
import framework.binding.PropertyBinder;
import framework.injection.DefaultInjectManager;
import framework.injection.IInjectManager;
import framework.injection.IInjectable;
import framework.view.components.Component;

/**
 * ComponentBuilder
 * @author jliang
 * 
 */
public class ComponentBuilder
{
	public function ComponentBuilder()
	{
	}
	//==========================================================================
	//  Variables
	//==========================================================================
	private static var injector:IInjectManager = DefaultInjectManager.getInstace();
	
	public function setInjector(value:IInjectManager):void
	{
		injector = value;
	}
	//==========================================================================
	//  Public methods
	//==========================================================================
	public static function create(classRef:Class):*
	{
		var component:* = new classRef();
		if (component is IInjectable)
		{
			injector.inject(component);
		}
		if (component is IBinder)
		{
			PropertyBinder.bind(component);
		}
		if (component is Component)
		{
			Component(component).initialize();
		}
		return component;
	}
	
	public static function createByDefineName(ref:String):*
	{
		var ui:DisplayObject = UIWidget.createUI(ref);
		if (ui is IInjectable)
		{
			injector.inject(IInjectable(ui));
		}
		if (ui is IBinder)
		{
			PropertyBinder.bind(ui);
		}
		if (ui is Component)
		{
			Component(ui).initialize();
		}
		return ui;
	}
	
	public static function createNonDisplayObject(ref:String):*
	{
		var classRef:Class = getClassByName(ref) as Class;
		var instance:* = new classRef();
		if (instance is IInjectable)
		{
			injector.inject(instance);
		}
		return instance;
	}
	
	public static function getClassByName(ref:String):Class
	{
		var domains:Dictionary = UIWidget.getApplicationDomains();
		
		for (var domainID:String in domains)
		{
			var domain:ApplicationDomain = domains[domainID];
			if (domain.hasDefinition(ref))
			{
				var classRef:Class = domain.getDefinition(ref) as Class;
				return classRef;
			}
		}
		return null;
	}
	
	public static function disposeComponent(component:*):void
	{
		if (component is IBinder)
		{
			PropertyBinder.unbind(component);
		}
	}
}
}